<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Expires" content="Fri, Jan 01 1900 00:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Lang" content="en">
<meta name="author" content="">
<meta http-equiv="Reply-to" content="@.com">
<meta name="generator" content="PhpED 5.8">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="creation-date" content="01/01/2009">
<meta name="revisit-after" content="15 days">
<title>Untitled</title>
<link rel="stylesheet" type="text/css" href="my.css">
</head>
<body>
<?php
/**
 * XML2Array: A class to convert XML to array in PHP
 * It returns the array which can be converted back to XML using the Array2XML script
 * It takes an XML string or a DOMDocument object as an input.
 *
 * See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
 *
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
 * License: Apache License 2.0
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.1 (07 Dec 2011)
 * Version: 0.2 (04 Mar 2012)
 *             Fixed typo 'DomDocument' to 'DOMDocument'
 *
 * Usage:
 *       $array = XML2Array::createArray($xml);
 */
 
class XML2Array 
{ 
    private static $xml = null;
    private static $encoding = 'UTF-8';
 
    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DOMDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
        self::$encoding = $encoding;
    }
 
    /**
     * Convert an XML to Array
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMDocument
     */
    public static function &createArray($input_xml) {
        $xml = self::getXMLRoot();
        if(is_string($input_xml)) {
            $parsed = $xml->loadXML($input_xml);
            if(!$parsed) {
                throw new Exception('[XML2Array] Error parsing the XML string.');
            }
        } else {
            if(get_class($input_xml) != 'DOMDocument') {
                throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
            }
            $xml = self::$xml = $input_xml;
        }
        $array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $array;
    }
 
    /**
     * Convert an Array to XML
     * @param mixed $node - XML as a string or as an object of DOMDocument
     * @return mixed
     */
    private static function &convert($node) {
        $output = array();
 
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
                $output['@cdata'] = trim($node->textContent);
                break;
 
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
 
            case XML_ELEMENT_NODE:
 
                // for each child node, call the covert function recursively
                for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
                    $child = $node->childNodes->item($i);
                    $v = self::convert($child);
                    if(isset($child->tagName)) {
                        $t = $child->tagName;
 
                        // assume more nodes of same kind are coming
                        if(!isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    } else {
                        //check if it is not an empty text node
                        if($v !== '') {
                            $output = $v;
                        }
                    }
                }
 
                if(is_array($output)) {
                    // if only one node of its kind, assign it directly instead if array($value);
                    foreach ($output as $t => $v) {
                        if(is_array($v) && count($v)==1) {
                            $output[$t] = $v[0];
                        }
                    }
                    if(empty($output)) {
                        //for empty nodes
                        $output = '';
                    }
                }
 
                // loop through the attributes and collect them
                if($node->attributes->length) {
                    $a = array();
                    foreach($node->attributes as $attrName => $attrNode) {
                        $a[$attrName] = (string) $attrNode->value;
                    }
                    // if its an leaf node, store the value in @value instead of directly storing it.
                    if(!is_array($output)) {
                        $output = array('@value' => $output);
                    }
                    $output['@attributes'] = $a;
                }
                break;
        }
        return $output;
    }
 
    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }
    
    /**
     * slug()
     * creates a slug from a string
     */
    static function slug($phrase) 
    {
        // Apply path as some name is Uppercase, we need to format to lowercase to create slug
        $phrase = strtolower($phrase);

        $find = array('á','à','ả','ã','ạ');
        $phrase = str_replace($find, 'a', $phrase);
		
		$find = array('â','ấ','ầ','ẩ','ẫ','ậ');
        $phrase = str_replace($find, 'a', $phrase);

        $find = array('í','ì','ỉ','ĩ','ị');
        $phrase = str_replace($find, 'i', $phrase);

        $find = array('é','è','ẻ','ẽ','ẹ');
        $phrase = str_replace($find, 'e', $phrase);

        $find = array('ê','ế','ề','ể','ễ','ệ');
        $phrase = str_replace($find, 'e', $phrase);

        $find = array('ý','ỳ','ỷ','ỹ','ỵ');
        $phrase = str_replace($find, 'y', $phrase);

        $find = array('ó','ò','ỏ','õ','ọ');
        $phrase = str_replace($find, 'o', $phrase);     

        $find = array('ô','ố','ồ','ổ','ỗ','ộ');
        $phrase = str_replace($find, 'o', $phrase);     

        $find = array('ơ','ớ','ờ','ở','ỡ','ợ');
        $phrase = str_replace($find, 'o', $phrase);     

        $find = array('ú','ù','ủ','ũ','ụ');
        $phrase = str_replace($find, 'u', $phrase);             

        $find = array('ư','ứ','ừ','ử','ữ','ự');
        $phrase = str_replace($find, 'u', $phrase);             

		//adding special case
		//đ
		$find = array('đ');
		$phrase = str_replace($find, 'd', $phrase); 

        $str = strtolower($phrase);

        // replace spaces with underscore, all to lowercase
        $str = strtolower(str_replace(' ', '_', $str));

        // create regex pattern
        $pattern = "/[^a-zA-Z0-9_]/";

        // replace non alphanumeric characters
        $str = preg_replace($pattern, '', $str);

        return $str;
    }
}

$xml_data = file_get_contents("http://cafef.vn/Doanh-nghiep.rss");
$data = XML2Array::createArray($xml_data);

$data = $data['rss']['channel']['item'];

$list_company = array('CII', 'CSM', 'DIG', 'DRC', 'GAS', 'HAG', 'HCM', 'HPG', 'HSG', 
'IJC', 'MSN', 'NTL', 'PHR', 'DPM', 'PGS', 'PVC', 'PVS', 'REE', 'SSI', 'VND',
'CNG',
);

$companies = array();

require_once "simple_html_dom.php";

foreach($data as $value)
{
    $str = "";
    $desc = "";
    $link = "";
    $pub = "";
    
    $pos = strpos($value['title']['@cdata'],":");
    if($pos !== false)
    {
        $str = substr($value['title']['@cdata'],0,$pos);
        $desc = $value['description']['@cdata'];          
        $link = $value['link'];          
        $pub = $value['pubDate'];          
    }
    
    if(in_array($str,$list_company))
    {
        $html = file_get_html($link);
        $detail = $html->find('div[class=KenhF_Content_News3]',0)->outertext;
        
        $companies[$str]['title'] = $value['title']['@cdata'];
        $companies[$str]['slug'] = XML2Array::slug($value['title']['@cdata']);
        $companies[$str]['company'] = $str;
        $companies[$str]['short_desc'] = $desc;
        $companies[$str]['created_date'] = date('Y-m-d',strtotime($pub));
        $companies[$str]['detail'] = $detail;
    }
}

/*echo "<pre>";
print_r($companies);
echo "</pre>";                     */

// open connection
$link = mysql_connect('localhost', 'ndhinves_test', 'Test1234'); // server
//$link = mysql_connect('localhost', 'root', ''); // local test
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('ndhinves_test', $link); // server
//$db_selected = mysql_select_db('ndhinvestors', $link); // local
if (!$db_selected) {
    die ('Can\'t use database : ' . mysql_error());
}

// set UTF-8
mysql_query("set names 'utf8'",$link);   

foreach($companies as $company)
{    
    $title = mysql_escape_string($company['title']);
    $slug = mysql_escape_string($company['slug']);
    $detail = mysql_escape_string($company['detail']);
    $company_name = mysql_escape_string($company['company']);
    $created_date = $company['created_date'];
    $modified_date = date('Y-m-d');
    $active = 1;
    $new_types_id = 5;
    $companies_id = 1;
    $companies_company_profiles_id = 1;
    
    // kiem tra xem tin tuc do da duoc insert hay chua
    $chk_query = "SELECT * FROM news WHERE title = '$title' ORDER BY id DESC LIMIT 1";
    $result = mysql_query($chk_query); 
    
    // chua insert, insert data
    if(mysql_num_rows($result) <= 0)
    {
        $query = "SELECT * FROM companies WHERE shortname = '$company_name' AND active = 1 LIMIT 1";
        $rst = mysql_query($query);
        while ($row = mysql_fetch_array($rst, MYSQL_ASSOC)) 
        {
            $companies_id = $row["id"];
            $companies_company_profiles_id = $row["company_profiles_id"];
        }  
    
        $insert_query = "INSERT INTO news (title,slug,detail,created_date,modified_date,active,new_types_id,companies_id,companies_company_profiles_id) 
                     VALUES ('$title','$slug','$detail','$created_date','$modified_date',$active,$new_types_id,$companies_id,$companies_company_profiles_id)";    
                     
        echo $insert_query."<br/>";
        if(!mysql_query($insert_query))
        {
            echo "can not insert data <br/>";
        }
    }
}

$sql = "SELECT * FROM news";
$result = mysql_query($sql);

$rows = array();
while($row = mysql_fetch_array($result))
{
    $rows[] = $row;
}

/*echo "<pre>";
print_r($rows);
echo "</pre>";       */

// close connection
mysql_close($link);
?>
</body>
</html>
